package com.cloudpivot.receivales.ding.scenegroup.controller;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.contract.domain.NormalReturn;
import com.cloudpivot.receivales.ding.scenegroup.domain.*;
import com.cloudpivot.receivales.ding.scenegroup.service.CoolAppService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

/**
 * 群相关 接口
 */
@Controller
@Slf4j
@RequestMapping("/saleapi/coolApp")
public class CoolAppController {

    @Autowired
    private CoolAppService coolAppService;

    /**
     * 推送Cool app 消息
     * @param dto
     */
    @PostMapping("/pushCoolAppMessageOnGroup")
    @ResponseBody
    public RspDTO pushCoolAppMessageOnGroup(@Validated @RequestBody CoolAppActionMsgDTO dto) {
        log.info("请求（CRM）创建场景群对象：{}", JSONObject.toJSONString(dto));
        //校验记录
        if(StringUtils.isBlank(dto.getOpenConversationId())){
            return new RspDTO(-102);
        }
        String ret = coolAppService.pushCoolappMsgOnGroup(dto);
        if (StringUtils.isBlank(ret)) {
            return new RspDTO(-102);
        }
        return new RspDTO(2, ret);
    }
    /**
     * 推送Cool app 消息
     * @param dto
     */
    @PostMapping("/pushCoolAppMessageOnSingle")
    @ResponseBody
    public RspDTO pushCoolAppMessageOnSingle(@Validated @RequestBody CoolAppActionMsgDTO dto) {
        log.info("请求（CRM）创建场景群对象：{}", JSONObject.toJSONString(dto));
        //校验记录
        if(StringUtils.isBlank(dto.getOpenConversationId())){
            return new RspDTO(-102);
        }
        String ret = coolAppService.pushCoolappMsgOnSingle(dto);
        if (StringUtils.isBlank(ret)) {
            return new RspDTO(-102);
        }
        return new RspDTO(2, ret);
    }

    /**
     * 推送Cool app hello消息
     * @param dto
     */
    @PostMapping("/pushCoolAppHelloMessage")
    @ResponseBody
    public RspDTO pushCoolAppHelloMessage(@Validated @RequestBody CoolAppActionMsgDTO dto) {
        log.info("请求（CRM）创建场景群对象：{}", JSONObject.toJSONString(dto));
        //校验记录
        if(StringUtils.isBlank(dto.getOpenConversationId())){
            return new RspDTO(-102);
        }
        String ret = coolAppService.pushHelloCoolappMsg(dto);
        if (StringUtils.isBlank(ret)) {
            return new RspDTO(-102);
        }
        return new RspDTO(2, ret);
    }



    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public NormalReturn exceptionHandler(MethodArgumentNotValidException e) {
        NormalReturn resultJson = new NormalReturn(-1, "error");
        resultJson.setMsg(e.getBindingResult().getFieldError().getDefaultMessage());
        return resultJson;
    }

}
